package com.ujiuye.filter;

import com.ujiuye.entity.UserInfo;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")//登录过滤器
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        //向下的类型强转
        HttpServletRequest req=(HttpServletRequest) request;
        HttpServletResponse resp=(HttpServletResponse)response;
        //获取请求路径
         String uri=req.getRequestURI();
         //截取获取最终的简化的请求路径
        String uriPath=uri.substring(uri.lastIndexOf("/")+1);
        if ("register.html".equals(uriPath)||"register".equals(uriPath)
                ||"login.jsp".equals(uriPath)||"login".equals(uriPath)){
            filterChain.doFilter(req,resp);
        }else {
            //需要进行登录安全校验
            HttpSession session = req.getSession();
            UserInfo user = (UserInfo)session.getAttribute("userInfo");
            if(user!=null){
                //登录成功
                filterChain.doFilter(req,resp);
            }else{
                //去登录
                resp.sendRedirect("login.jsp");
            }
        }
    }
    @Override
    public void destroy() {

    }
}
